package com.along.framework.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;

/** 
 * Request相关方法
 * Copyright 2010
 * @author linliming
 * @date 2010-04-19 
 */
@SuppressWarnings("unchecked")
public class ReqFuncs {

	//
	public static String getStringParam(HttpServletRequest request, String paramName) {
		return getStringParam(request, paramName, null);
	}

	public static String[] getStringParams(HttpServletRequest request, String paramName) {
		String[] sValues = request.getParameterValues(paramName);
		if (sValues == null) {
			sValues = new String[]{};
		}
		return sValues;
	}

	public static String getStringParam(HttpServletRequest request, String paramName, String defaultValue) {
		String result = request.getParameter(paramName);
		if (result == null || result.length() == 0) {
			result = defaultValue;
		}
		return result;
	}

	//
	public static Integer getIntegerParam(HttpServletRequest request, String paramName) {
		return getIntegerParam(request, paramName, null);
	}

	public static Integer getIntegerParam(HttpServletRequest request, String paramName, Integer defaultValue) {
		String sParam = request.getParameter(paramName);
		Integer result;
		try {
			result = Integer.parseInt(sParam);
		}
		catch (NumberFormatException nfe) { // null or bad format
			result = defaultValue;
		}
		return result;
	}
	public static boolean hasParam(HttpServletRequest request, String paramName) {
		return request.getParameter(paramName) != null;
	}
	public static Double getDoubleParam(HttpServletRequest request, String paramName) {
		return getDoubleParam(request, paramName, null);
	}
	public static Double getDoubleParam(HttpServletRequest request, String paramName, Double defaultValue) {
		String sParam = request.getParameter(paramName);
		Double result;
		try {
			result = Double.parseDouble(sParam);
		}
		catch (NumberFormatException nfe) { // null or bad format
			result = defaultValue;
		}
		return result;
	}
	
	public static Double[] getDoubleParams(HttpServletRequest request, String paramName) {
		String[] sValues = request.getParameterValues(paramName);
		if (sValues == null)
			return new Double[]{};
		Double[] values = new Double[sValues.length];
		for (int n = 0; n < sValues.length; n++) {
			values[n] = Double.valueOf(sValues[n]);
		}
		return values;
	}
	
	public static BigDecimal getBigDecimalParam(HttpServletRequest request, String paramName) {
		return getBigDecimalParam(request, paramName, null);
	}
	
	public static BigDecimal getBigDecimalParam(HttpServletRequest request, String paramName, BigDecimal defaultValue) {
		String sParam = request.getParameter(paramName);
		BigDecimal result;
		try {
			result = new BigDecimal(sParam);
		}
		catch (NumberFormatException nfe) { // null or bad format
			result = defaultValue;
		}
		return result;
	}
	
	public static BigDecimal[] getBigDecimalParams(HttpServletRequest request, String paramName) {
		String[] sValues = request.getParameterValues(paramName);
		if (sValues == null)
			return new BigDecimal[]{};
		BigDecimal[] values = new BigDecimal[sValues.length];
		for (int n = 0; n < sValues.length; n++) {
			values[n] = new BigDecimal(sValues[n]);
		}
		return values;
	}

	public static Integer[] getIntegerParams(HttpServletRequest request, String paramName) {
		String[] sValues = request.getParameterValues(paramName);
		if (sValues == null)
			return new Integer[]{};
		Integer[] values = new Integer[sValues.length];
		for (int n = 0; n < sValues.length; n++) {
			values[n] = Integer.parseInt(sValues[n]);
		}
		return values;
	}

	//
	public static String getUrl(HttpServletRequest request) {
		return getUrl(request, true);
	}
	public static String getUrl(HttpServletRequest request, boolean considerInclude) {
		StringBuffer url = new StringBuffer();
		String qs;

		String includedUri = (String) request.getAttribute("javax.servlet.include.request_uri");
		if (includedUri != null && considerInclude) {
			url.append(includedUri);
			qs = (String) request.getAttribute("javax.servlet.include.query_string");
		}
		else {
			url.append(request.getRequestURL());
			qs = request.getQueryString();
		}
		String jsnid = (String) request.getSession().getAttribute("JSNID");
		if (jsnid != null) {
			url.append(jsnid);
		}
		if (qs != null && qs.length() > 0) {
			url.append('?');
			url.append(qs);
		}
		if (url.charAt(0) == '/') {
			return url.toString();
		}
		return url.substring(url.indexOf("/", 8));
	}

	public static boolean isIncluded(HttpServletRequest request) {
		return request.getAttribute("javax.servlet.include.request_uri") != null;
	}



	private static Map checkFieldMarkers(Map<String, Object> map) {
		List<String> markerFields = new ArrayList<String>();
		for (String key : map.keySet()) {
			if (key.startsWith("_")) {
				String realKey = key.substring(1);
				if (!map.containsKey(realKey)) {
					markerFields.add(key);
				}
			}
		}
		if (markerFields.size() == 0) {
			return map;
		}
		HashMap<String, Object> newMap = new HashMap(map);
		for (String key : markerFields) {
			String realKey = key.substring(1);
			Object value = map.get(key);
			// if (value.getClass().isArray()) {
			// //map.get(key)
			// System.out.println("?");
			// }
			newMap.put(realKey, value);
		}
		return newMap;
	}

	

	//
	public static void setRequestData(HttpServletRequest request, Object data) {
		setRequestData(request, data.getClass().getName(), data);
	}

	public static void setRequestData(HttpServletRequest request, String key, Object data) {
		request.setAttribute(key, data);
		setRequestDataForRedirect(request, key, data);
	}

	private static void setRequestDataForRedirect(HttpServletRequest request, String key, Object data) {
		HttpSession session = request.getSession();
		Map map = (Map) session.getAttribute("REQUEST_DATA_MAP_FOR_REDIRECT");
		map.put(key, data);
	}

	public static <T> T getRequestData(HttpServletRequest request, Class<T> clazz) {
		return (T) request.getAttribute(clazz.getName());
	}

	//
	public static void setSessionData(HttpServletRequest request, Object data) {
		request.getSession().setAttribute(data.getClass().getName(), data);
	}

	public static void setSessionData(HttpServletRequest request, String key, Object data) {
		request.getSession().setAttribute(key, data);
	}

	public static <T> T getSessionData(HttpServletRequest request, Class<T> clazz) {
		return (T) request.getSession().getAttribute(clazz.getName());
	}

	public static <T> T getSessionData(HttpServletRequest request, String key, Class<T> clazz) {
		return (T) request.getSession().getAttribute(key);
	}

	public static <T> T getSessionData(HttpServletRequest request, Class<T> clazz, String key) {
		return (T) request.getSession().getAttribute(key);
	}



	public static String getReferer(HttpServletRequest request) {
		return request.getHeader("referer");
	}

	//
	public static Map<String, String> getCookieMap(HttpServletRequest request) {
		Map<String, String> result = new HashMap<String, String>();
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				result.put(cookie.getName(), cookie.getValue());
			}
		}
		return result;
	}

	

	//检查url
	public static String checkUrl(String pageUrl) throws UnsupportedEncodingException {
		pageUrl = java.net.URLDecoder.decode(pageUrl, "utf-8");
		pageUrl.replaceAll("&amp;", "&");
		pageUrl.replaceAll("&", "&amp;");

		return pageUrl;
	}
	//获取应用的路径
	public static String formatUrl(HttpServletRequest request, String strUrl) throws UnsupportedEncodingException {
		String webapp = request.getRequestURI().substring(0, request.getRequestURI().indexOf(request.getServletPath()));
		strUrl = strUrl.replaceFirst(webapp, "");

		return strUrl;
	}
}
